#include "stm32f4xx.h"
#include "stm32f4xx_ll_cortex.h"
#include "stm32f4xx_ll_utils.h"

unsigned long g_ll_tick;

void LL_Tick_Handler()
{
    g_ll_tick++;
    //lv_tick_inc(1);
    if(g_ll_tick%5 == 0)
    {
        //lv_timer_handler();
    }
}

unsigned long LL_GetTick()
{
    return g_ll_tick;
}

void LL_Tick_Init()
{
    LL_Init1msTick(168000000);
    // 配置中断处理
    NVIC_SetVector(SysTick_IRQn, LL_Tick_Handler);
    NVIC_SetPriority(SysTick_IRQn, 15);
    NVIC_EnableIRQ(SysTick_IRQn);
    // 使能systick中断
    SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk;
    
}

void LL_Init1usTick(unsigned int HCLKFrequency)
{
    /* Use frequency provided in argument */
    LL_InitTick(HCLKFrequency, 1000000U);
}

void LL_uDelay(unsigned int Delay)
{
    __IO uint32_t tmp = SysTick->CTRL; /* Clear the COUNTFLAG first */
    /* Add this code to indicate that local variable is not used */
    ((void)tmp);

    /* Add a period to guaranty minimum wait */
    if (Delay < LL_MAX_DELAY)
    {
        Delay++;
    }

    while (Delay)
    {
        if ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) != 0U)
        {
            Delay--;
        }
        // if(Delay%1000000 == 0)
        //     printf("delay %d\n", Delay);
    }
}

// 由于没有使用hal库中的HAL_InitTick相关函数，这里需要重写HAL_IncTick HAL_GetTick
// 这两个函数和HAL_Delay息息相关，同时很多hal库代码中用到了这两个函数
void HAL_IncTick(void)
{
    g_ll_tick++;
}

unsigned int HAL_GetTick(void)
{
    return g_ll_tick;
}